package fx;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.jfoenix.controls.JFXListView;
import com.jfoenix.controls.JFXTextField;
import fx.componet.*;
import fx.data.PlayItem;
import javafx.animation.TranslateTransition;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.ListCell;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.text.Font;
import javafx.scene.text.FontSmoothingType;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.util.Duration;
import lombok.extern.java.Log;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;

import static fx.ResourceFactory.from;

@Log
public class NetEaseMusicApplication extends Application {
    boolean firstTime = true;

    @Override
    public void start(Stage primaryStage) {
        log.info("主应用启动");
        //主容器
        MyAnchorPane mainPane = new MyAnchorPane();
        mainPane.setStyle("-fx-border-radius: 5px;-fx-border-width: 1px;");

        //顶部栏位
        MyAnchorPane topPane = new MyAnchorPane();
        topPane.setPrefHeight(62);
        topPane.setStyle("-fx-background-color: #EC4141;-fx-border-radius: 10px");
        topPane.withDrag(primaryStage);
        topPane.anchor(0.0, null, 0.0, 0.0);

        ImageViewWithHoverEvent icon = new ImageViewWithHoverEvent(from("musicIcon.png"));
        icon.fitSize(40, 40);
        icon.autosize();
        icon.anchor(null, 10.0, 10.0, 30.0);

        MyText title = new MyText("我的云音乐", false);
        title.setFont(Font.font(30));
        title.setStyle("-fx-font-family: KaiTi");
        title.setFill(Color.WHITE);
        title.anchor(null, 8.0, 12.0, 80.0);

        JFXTextField search = new JFXTextField();
        search.setPrefSize(260, 40);
        search.focusedProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue && firstTime) {
                title.requestFocus(); // Delegate the focus to container
                firstTime = false;
            }
        });
        AnchorPane.setRightAnchor(search, 155.0);


        //关闭按钮
        ImageViewWithHoverEvent closeButton = new ImageViewWithHoverEvent(from("close.png"), from("closeHover.png"));
        closeButton.fitSize(20, 20);
        closeButton.setOnMouseClicked(event -> stop());
        closeButton.anchor(25.0, 21.0, 21.0, null);

        //最小化按钮
        ImageViewWithHoverEvent minButton = new ImageViewWithHoverEvent(from("min.png"), from("minHover.png"));
        minButton.anchor(55.0, 21.0, 21.0, null);
        minButton.fitSize(20, 20);
        minButton.setOnMouseClicked(event -> primaryStage.setIconified(true));

        //换肤按钮
        ImageViewWithHoverEvent huanfu = new ImageViewWithHoverEvent(from("huanfu.png"), from("huanfuHover.png"));
        huanfu.fitSize(30, 30);
        huanfu.anchor(85.0, 16.0, 16.0, null);

        topPane.addEle(closeButton)
                .addEle(minButton)
                .addEle(huanfu)
                .addEle(search)
                .addEle(icon)
                .addEle(title);


        //侧边导航栏
        // x - y + z = 90
        // x - z + y = 50
        MyAnchorPane leftPane = new MyAnchorPane();
        leftPane.setPrefWidth(200);
        leftPane.setStyle("-fx-background-color: white");
        leftPane.anchor(null, 68.0, 62.0, 0.0);
        VBox labelButton = new VBox();
        Pane item = new Pane(new JFXTextField("发现音乐"));
        ObservableList<Node> children = labelButton.getChildren();
        children.add(item);

        leftPane.addEle(labelButton);

        //底部栏位
        MyAnchorPane bottomPane = new MyAnchorPane();
        bottomPane.setPrefHeight(62);
//        bottomPane.setStyle("-fx-background-color: gray");
        bottomPane.anchor(0.0, 0.0, null, 0.0);

        //播放栏专辑图片
        ImageViewWithHoverEvent zhuanjiImg = new ImageViewWithHoverEvent(new Image("http://p3.music.126.net/wJKwqM5wpgQr0gerroTMUA==/109951166230902150.jpg?param=50y50"));
        zhuanjiImg.fitSize(50, 50);
        zhuanjiImg.anchor(null, 6.0, 6.0, 25.0);
        zhuanjiImg.setClip(
                new Circle(zhuanjiImg.getX() + zhuanjiImg.getFitWidth() / 2,
                        zhuanjiImg.getY() + zhuanjiImg.getFitHeight() / 2, 25));

        //播放专辑名称
        MyText zhuanjiName = new MyText("男儿当自强男儿当自强男儿当自强男儿当自强男儿当自强男儿当自强", false);
        zhuanjiName.setFont(Font.font(20));
        zhuanjiName.setFontSmoothingType(FontSmoothingType.GRAY);
        zhuanjiName.setStyle("-fx-font-family: FangSong");
        zhuanjiName.setFill(Color.web("black", 0.9));
        zhuanjiName.anchor(null, 21.0, 21.0, 80.0);

        //进度条和播放控件
        MyAnchorPane controllerPane = new MyAnchorPane();
        controllerPane.setPrefHeight(62);
        controllerPane.setPrefWidth(500);
        controllerPane.setStyle("-fx-background-color: #fff");
        controllerPane.anchor(null, 0.0, 0.0, 275.0);

        //播放进度条
        MyJFXProgressBar progressBar = new MyJFXProgressBar();
        progressBar.setPrefWidth(400);
        progressBar.setCursor(Cursor.HAND);
        progressBar.anchor(null, null, 50.0, 50.0);

        MyText usedDuration = new MyText("0:00");
        usedDuration.anchor(null, 0.0, 42.0, 10.0);

        MyText totalDuration = new MyText("0:00");
        totalDuration.anchor(10.0, 0.0, 42.0, null);

        //控件
        MyHbox controllerList = new MyHbox();
        controllerList.setAlignment(Pos.CENTER);
        controllerList.setPrefWidth(280);
        controllerList.setMaxWidth(280);
        controllerList.anchor(null, null, 15.0, 90.0);
        ImageViewWithHoverEvent playButton = createImageViewWithMargin(25, 25, from("pause.png"), from("pauseHover.png"), new Insets(0, 0, 0, 25));
        controllerList.addEle(createImageViewWithMargin(25, 25, from("cycle.png"), from("cycleHover.png"), new Insets(0, 0, 0, 25)))
                .addEle(createImageViewWithMargin(25, 25, from("pre.png"), from("preHover.png"), new Insets(0, 0, 0, 25)))
                .addEle(playButton)
                .addEle(createImageViewWithMargin(25, 25, from("next.png"), from("nextHover.png"), new Insets(0, 0, 0, 25)))
                .addEle(createImageViewWithMargin(25, 25, from("ci.png"), from("ciHover.png"), new Insets(0, 0, 0, 25)));

        controllerPane
                .addEle(controllerList)
                .addEle(totalDuration)
                .addEle(usedDuration)
                .addEle(progressBar);
        ImageView swiper = new ImageView("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg95.699pic.com%2Fphoto%2F40133%2F5351.gif_wh300.gif%21%2Fgifto%2Ftrue&refer=http%3A%2F%2Fimg95.699pic.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1631809714&t=81dcfe10b094250118b1dbecb21c18c6");
        swiper.setFitHeight(150);
        swiper.setFitWidth(620);
        swiper.setTranslateX(100);
        TranslateTransition transition = new TranslateTransition();
        transition.setDuration(Duration.seconds(3));
        transition.setNode(swiper);
        transition.setFromX(300);
        transition.setToX(0);
        transition.play();
        AnchorPane.setTopAnchor(swiper, 62.0);
        AnchorPane.setLeftAnchor(swiper, 300.0);

        Media media = new Media("https://m701.music.126.net/20210816054811/7cd3c8c2c43c14f76cb7352749dd335b/jdymusic/obj/wo3DlMOGwrbDjj7DisKw/5153024748/1071/9366/6455/b6c9c0426e7183e53d9422402993110e.mp3");
        MediaPlayer mediaPlayer = new MediaPlayer(media);
        MyMediaView mediaView = new MyMediaView(mediaPlayer);
        mediaView.needUpdateEleList(progressBar, usedDuration, totalDuration);
        mediaView.schedule();
        playButton.setOnMouseClicked(event -> mediaView.doPlay());

        mediaView.getMediaPlayer().setOnEndOfMedia(() -> {
            System.out.println("播放结束 ...");
            MediaPlayer player = mediaView.getMediaPlayer();
            if (player != null) {
                player.dispose();
            }
            MediaPlayer newPlayer = new MediaPlayer(new Media("https://m701.music.126.net/20210816054811/7cd3c8c2c43c14f76cb7352749dd335b/jdymusic/obj/wo3DlMOGwrbDjj7DisKw/5153024748/1071/9366/6455/b6c9c0426e7183e53d9422402993110e.mp3"));
            newPlayer.setOnEndOfMedia(mediaView.getMediaPlayer().getOnEndOfMedia());
            mediaView.setPlayer(newPlayer);
            mediaView.setPlaying(false);
            mediaView.doPlay();
        });

        JFXListView<PlayItem> jfxListView = new JFXListView<>();
        jfxListView.getStyleClass().add("-fx-background-color: transparent;");
        jfxListView.setPrefWidth(820);
        //自定义显示内容
        jfxListView.setCellFactory(param -> new ListCell<PlayItem>() {
            @Override
            protected void updateItem(PlayItem item, boolean empty) {
                super.updateItem(item, empty);
                if (item != null && !empty) {
                    this.setText(item.getName());
                }
            }
        });
        jfxListView.focusedProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue) {
                title.requestFocus(); // Delegate the focus to container
                firstTime = false;
            }
        });
        jfxListView.getSelectionModel().getSelectedItems().addListener((ListChangeListener<PlayItem>) c -> {
            boolean next = c.next();
            if (next) {
                System.out.println(c.getAddedSubList());
                System.out.println(JSONUtil.toJsonStr(c));
                try {
                    String mp3Url = Fetcher.searchById(c.getAddedSubList().get(0).getId());
                    MediaPlayer newnew = new MediaPlayer(new Media(mp3Url));
                    newnew.setAutoPlay(true);
                    mediaView.setMediaPlayer(newnew);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        AnchorPane.setBottomAnchor(jfxListView, 68.0);
        AnchorPane.setLeftAnchor(jfxListView, 200.0);
        AnchorPane.setTopAnchor(jfxListView, 212.0);
        search.setOnKeyPressed(event -> {
            KeyCode code = event.getCode();
            if (KeyCode.ENTER == code) {
                String word = search.getText();
                System.out.println("搜索词 =+- " + word);
                log.info("---- " + word);
                try {
                    Fetcher.search(word);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                JSONObject jsonObject = JSONUtil.parseObj(FileUtil.readString(new File("C:\\Users\\zxh\\IdeaProjects\\netEaseMusic\\target\\a.json"), Charset.defaultCharset()));
                JSONArray byPath = (JSONArray) jsonObject.getByPath("$.result.songs");
                for (Object object : byPath) {
                    JSONObject newo = (JSONObject) object;
                    PlayItem playItem = new PlayItem();
                    playItem.setName(newo.getStr("name"));
                    playItem.setId(newo.getLong("id"));
                    jfxListView.getItems().add(playItem);
                }
                System.out.println(jsonObject);
            }
        });


        bottomPane.addEle(zhuanjiImg)
                .addEle(zhuanjiName)
                .addEle(controllerPane)
                .addEle(mediaView);

        mainPane.addEle(topPane)
                .addEle(bottomPane)
                .addEle(leftPane)
                .addEle(jfxListView)
                .addEle(swiper);

        Scene scene = new Scene(mainPane, 1020, 670);
        scene.getStylesheets().add(
                this.getClass().getResource("/css/listView.css").toExternalForm());
        primaryStage.setScene(scene);
        primaryStage.initStyle(StageStyle.UNDECORATED);
        primaryStage.setAlwaysOnTop(true);
        primaryStage.show();
    }

    @Override
    public void init() throws Exception {
        log.info("应用启动");
    }

    @Override
    public void stop() {
        log.info("应用关闭");
        Platform.exit();
    }

    private ImageViewWithHoverEvent createImageViewWithMargin(double h, double w, Image defaultImg, Image hoverImg, Insets insets) {
        ImageViewWithHoverEvent imageViewWithHoverEvent = new ImageViewWithHoverEvent(defaultImg, hoverImg);
        imageViewWithHoverEvent.fitSize(w, h);
        HBox.setMargin(imageViewWithHoverEvent, insets);
        return imageViewWithHoverEvent;
    }

}
